package com.turboconnard.events;

import java.util.ArrayList;

public class EventDispatcher {
	ArrayList<ArrayList<EventListener>> listeners;
	ArrayList<String> events;

	public void addEventListener(String event, EventListener listener) {
		createVectors();
		if (!events.contains(event)) {
			events.add(event);
			ArrayList<EventListener> t = new ArrayList<EventListener>();
			t.add(listener);
			listeners.add(t);
		} else {
			int id = events.lastIndexOf(event);
			listeners.get(id).add(listener);
		}
	}

	private void createVectors() {
		// TODO Auto-generated method stub
		if (listeners == null) {
			listeners = new ArrayList<ArrayList<EventListener>>();
			events = new ArrayList<String>();
		}
	}

	public void removeEventListener(EventListener listener) {
		listeners.remove(listener);
	}

	public void dispatchEvent(Event e) {
		createVectors();
		e.target = this;	
		if(events.size()>0){
			int id = events.lastIndexOf(e.name);
			ArrayList<EventListener> al = listeners.get(id);
			for (int i = al.size() - 1; i > -1; i--) {
				al.get(i).event(e);
			}
		}
	}
	public void removeAllListeners(){
		if(listeners!=null)	listeners.clear();
		if(events!=null) events.clear();
	}
}
